package com.myfoon.servlet.pub;

import com.myfoon.helper.SessionHelper;
import com.myfoon.model.ejb.EventEJBLocal;

import com.myfoon.model.entity.User;
import com.myfoon.model.entity.result.EventOfFriend;
import com.myfoon.utils.JSONUtils;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.ejb.EJB;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

public class Events extends HttpServlet {
    @EJB  
    EventEJBLocal eventLocal;
    
    public Events() {
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
                                                                          IOException {
        String start = httpServletRequest.getParameter("start");
        Integer st = start == null ? 0 : Integer.parseInt(start);
        SessionHelper sessionHelper = new SessionHelper(httpServletRequest);        
        User user = sessionHelper.getUser();
        Integer tzOffset = sessionHelper.getTimeZoneOffset();
        
        List<EventOfFriend> eventsOfFriends = eventLocal.getLastEvents(user, tzOffset, true, st, 15);        
        JSONObject JSONConvertedEvents = new JSONUtils().convertFromEventOfFriends(eventsOfFriends);                                         
            
        PrintWriter writer = httpServletResponse.getWriter();        
        writer.println(JSONConvertedEvents.toString());
        writer.flush();
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse) throws ServletException,
                                                                         IOException {
        doPost(httpServletRequest, httpServletResponse);
    }
}
